<?php

/**
 * This is the model class for table "lths_trade_treaty".
 *
 * The followings are the available columns in table 'lths_trade_treaty':
 * @property integer $id
 * @property string $trade_date
 * @property string $trade_staff
 * @property integer $trade_method
 * @property integer $trade_user_type
 * @property integer $producttype_code
 * @property string $product_id
 * @property string $imei
 * @property integer $inchannel_code
 * @property string $serialnumber
 * @property integer $treatyyear
 * @property integer $discnt_code
 * @property integer $trade_number
 * @property double $bill_fee
 * @property double $phone_fee
 * @property double $card_fee
 * @property double $rbill_fee
 * @property double $all_fee
 * @property double $check_money
 * @property double $ready_money
 * @property double $pos_money
 * @property double $discount_money
 * @property double $trade_money
 * @property double $discount_minus
 * @property string $remark
 * @property string $update_staff
 * @property string $create_time
 * @property string $update_time
 *
 * The followings are the available model relations:
 * @property BDiscnt $discntCode
 * @property BInchannel $inchannelCode
 * @property Producttype $producttypeCode
 * @property Product $product
 * @property User $tradeStaff
 * @property BTrademethod $tradeMethod
 * @property BUsertype $tradeUserType
 */
class TradeTreaty extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return TradeTreaty the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'lths_trade_treaty';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('trade_date,trade_staff, trade_method, trade_user_type, producttype_code, product_id, inchannel_code, treatyyear, discnt_code, trade_number', 'required'),
			array('trade_method, trade_user_type, producttype_code, inchannel_code, treatyyear, discnt_code, trade_number', 'numerical', 'integerOnly'=>true),
			array('bill_fee, phone_fee, card_fee, rbill_fee, all_fee, check_money, ready_money, pos_money, discount_money, trade_money, discount_minus', 'numerical'),
			array('trade_staff, serialnumber', 'length', 'max'=>20),
			array('product_id', 'length', 'max'=>15),
			array('imei', 'length', 'max'=>50),
			array('remark', 'length', 'max'=>500),
			array('create_time, update_time, update_staff', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, trade_date, trade_staff, trade_method, trade_user_type, producttype_code, product_id, imei, inchannel_code, serialnumber, treatyyear, discnt_code, bill_fee, phone_fee, card_fee, rbill_fee, all_fee, check_money, ready_money, pos_money, discount_money, trade_money, discount_minus, remark, create_time, update_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'discntCode' => array(self::BELONGS_TO, 'BDiscnt', 'discnt_code'),
			'inchannelCode' => array(self::BELONGS_TO, 'BInchannel', 'inchannel_code'),
			'producttypeCode' => array(self::BELONGS_TO, 'Producttype', 'producttype_code'),
			'product' => array(self::BELONGS_TO, 'Product', 'product_id'),
			'tradeStaff' => array(self::BELONGS_TO, 'User', 'trade_staff'),
			'tradeMethod' => array(self::BELONGS_TO, 'BTrademethod', 'trade_method'),
			'tradeUserType' => array(self::BELONGS_TO, 'BUsertype', 'trade_user_type'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'trade_date' => '日期',
			'trade_staff' => '销售人',
			'trade_method' => '销售方式',
			'trade_user_type' => '用户类别',
			'producttype_code' => '产品类型',
			'product_id' => '规格型号',
			'imei' => '串号',
			'inchannel_code' => '产品来源',
			'serialnumber' => '手机号码',
			'treatyyear' => '合约期',
			'discnt_code' => '套餐保底',
			'trade_number' => '销售数量',
			'bill_fee' => '合约预存款',
			'phone_fee' => '优惠购机款',
			'card_fee' => '卡费',
			'rbill_fee' => '额外预存款',
			'all_fee' => '合计',
			'check_money' => '支票',
			'ready_money' => '现金',
			'pos_money' => 'POS机刷卡',
			'discount_money' => '折扣',
			'trade_money' => '实收金额',
			'discount_minus' => '折扣核减',
			'remark' => '备注',
			'create_time' => 'Create Time',
			'update_time' => 'Update Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('trade_date',$this->trade_date,true);
		$criteria->compare('trade_staff',$this->trade_staff,true);
		$criteria->compare('trade_method',$this->trade_method);
		$criteria->compare('trade_user_type',$this->trade_user_type);
		$criteria->compare('producttype_code',$this->producttype_code);
		$criteria->compare('product_id',$this->product_id,true);
		$criteria->compare('imei',$this->imei,true);
		$criteria->compare('inchannel_code',$this->inchannel_code);
		$criteria->compare('serialnumber',$this->serialnumber,true);
		$criteria->compare('treatyyear',$this->treatyyear);
		$criteria->compare('discnt_code',$this->discnt_code);
		$criteria->compare('bill_fee',$this->bill_fee);
		$criteria->compare('phone_fee',$this->phone_fee);
		$criteria->compare('card_fee',$this->card_fee);
		$criteria->compare('rbill_fee',$this->rbill_fee);
		$criteria->compare('all_fee',$this->all_fee);
		$criteria->compare('check_money',$this->check_money);
		$criteria->compare('ready_money',$this->ready_money);
		$criteria->compare('pos_money',$this->pos_money);
		$criteria->compare('discount_money',$this->discount_money);
		$criteria->compare('trade_money',$this->trade_money);
		$criteria->compare('discount_minus',$this->discount_minus);
		$criteria->compare('remark',$this->remark,true);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function onAfterSave($event)
	{
	    
	    $profitModel = new Profit;
	    $profitModel->attributes=array(
	    	'trade_date'       => $this->trade_date,
	    	'trade_staff'      => $this->trade_staff,
			'trade_method'     => $this->trade_method,
			'trade_user_type'  => $this->trade_user_type,
			'producttype_code' => $this->producttype_code,
			'product_id'       => $this->product_id,
			'bill_fee'         => $this->bill_fee,
			'phone_fee'        => $this->phone_fee,
			'check_profit'     => $this->getCheckProfit(),
			//'real_profit'      =>,
			//'remark'           =>,
			'treaty_id'        => $this->id,
			//'general_id'       =>,
			'trade_type'       => 0,
	    );
	    
	    $profitModel->save();
	    
	}
	
	private function getCheckProfit()
	{
		$checkProfit=0;
		
		if($this->trade_method==1&&$this->trade_user_type==1)
		{
			switch($this->producttype_code)
			{
				case 1:
					$checkProfit=($this->bill_fee)*0.1;//iphone预存合约:合约预存款*0.1
					break;
				case 6:
					$checkProfit=($this->bill_fee)*0.18;//定制智能终端预存合约:合约预存款*0.18
					break;
				case 2:
					$checkProfit=80;//iPhone购机入网送话费:80
					break;
				case 7:
					$checkProfit=80;//定制智能终端购机入网送话费:80
					break;
				case 19:
					$checkProfit=50;//非定制终端购机入网送话费:50
					break;
				case 17:
					$checkProfit=10;//3G后付费单号:10
					break;
				case 25:
					$checkProfit=10;//自备机存费送费:10
					break;
				case 9:
					$checkProfit=($this->bill_fee*$this->trade_number)*0.4;//2G号卡:合约预存款*0.4
					break;
				case 11:
					$checkProfit=599*0.18;//599预付费购机合约:599*.18
					break;
				case 13:
					$checkProfit=($this->bill_fee)*0.2;//预付费无线上网卡:合约预存款*0.2
					break;
				case 14:
					$checkProfit=($this->bill_fee)*0.2;//后付费上网卡开户:合约预存款*0.2
					break;
			}
		}
		if($this->trade_method==3&&$this->trade_user_type==1)
		{
			switch($this->producttype_code)
			{
				case 1:
					$checkProfit=($this->bill_fee-$this->discount_money)*0.1;//iphone预存合约:（合约预存款-折扣）*0.1
					break;
				case 6:
					$checkProfit=($this->bill_fee-$this->discount_money)*0.18;//定制智能终端预存合约:（合约预存款-折扣）*0.18
					break;
				case 13:
					$checkProfit=($this->bill_fee-$this->discount_money)*0.2;//预付费无线上网卡:（合约预存款-折扣）*0.2
					break;
				case 14:
					$checkProfit=($this->bill_fee-$this->discount_money)*0.2;//后付费上网卡开户:（合约预存款-折扣）*0.2
					break;
			}
		}
		if (in_array($this->product_id, array('XN00002'))) //飞翔卡毛利计算公式单独修改为:合约预存款*0.4
		{
			$checkProfit=($this->bill_fee*$this->trade_number)*0.4;
		}
		return $checkProfit;
	}
	
	protected function beforeDelete()
	{
		Yii::log('onBeforeDelete','info');
		if(parent::beforeDelete())
		{
			Profit::model()->deleteAll('treaty_id='.$this->id);
			return true;
		}
		else
			return false;
	}
	
	public function behaviors(){  
    return array(  
        'CTimestampBehavior' => array(  
            'class' => 'zii.behaviors.CTimestampBehavior',  
            'createAttribute' => 'create_time',  
            'updateAttribute' => 'update_time',  
        )  
      );  
    }  
    
}